package com.fingard.dsp.bank.directbank.abc02;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ICurrencyExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.ReqQryExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.RetAtsExchange;
import com.fingard.dsp.bank.reqrespobj.currencyexchange.detail.RetAtsExchangeDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.MFSHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

////农行购汇（未测）
public class ABC02PurchaseExchange extends ABC02Base implements ICurrencyExchange {
    @Override
    public RetAtsExchange exchangePay(ReqExchange exchangePay) throws Exception {
        RetAtsExchange retAts = new RetAtsExchange(exchangePay.reqHeader);
        RetAtsExchangeDetail retDetail = new RetAtsExchangeDetail();
        try {
            //赋值通用参数
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "CFPT03";
            bankHeader.ReqSeqNo = exchangePay.singleDetail.askNumber;
            bankHeader.ReqDateTime = exchangePay.singleDetail.getPayDateTime();
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeElementString("Amt", exchangePay.singleDetail.payAmount);
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbProv", exchangePay.singleDetail.payAreaCode);
            xmlWriter.writeElementString("DbAccNo", getAbcAccNo(exchangePay.singleDetail.payAct));
            xmlWriter.writeElementString("DbCur", "01");//默认为人民币
            xmlWriter.writeElementString("CrProv", exchangePay.singleDetail.recAreaCode);
            xmlWriter.writeElementString("CrAccNo", getAbcAccNo(exchangePay.singleDetail.recAct));
            xmlWriter.writeElementString("CrCur", this.convertCurToBank(exchangePay.singleDetail.recCur));//
            xmlWriter.writeEndElement();
            XElement tmpXElement = new XElement("Corp","");
            tmpXElement.addChild(new XElement("StatCod",exchangePay.singleDetail.exchangeType));//结售汇统计代码 todo 结售汇代码表.xsl
            tmpXElement.addChild(new XElement("Postscript",exchangePay.singleDetail.abstractATS));
            tmpXElement.addChild(new XElement("TrDate", com.fingard.constant.Format.Date8Format.format(new Date())));
            tmpXElement.addChild(new XElement("CrAccName", exchangePay.singleDetail.recName));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeStartElement("atii");
            xmlWriter.writeElementString("CUSTNM", exchangePay.singleDetail.payName);
            xmlWriter.writeElementString("REGNO", exchangePay.singleDetail.businessNum);//外汇局批件号/备案表号/业务编号
            xmlWriter.writeElementString("TXCODE", exchangePay.singleDetail.transCode);//交易编码
            xmlWriter.writeElementString("USETYPE", exchangePay.singleDetail.purpose);//结汇用途 todo 可能需要添加字段枚举 可空
            xmlWriter.writeElementString("USEDETAIL", "");//结汇详细用途
            xmlWriter.writeElementString("CRTUSER", exchangePay.singleDetail.contactPerson);//填报人
            xmlWriter.writeElementString("INPTELC", exchangePay.singleDetail.contactNum);//填报人电话
            xmlWriter.writeElementString("OPPBANK", "");//买入币种开户行
            xmlWriter.writeEndElement();


            xmlWriter.writeEndDocument();//写入报文完成
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
            if(tmpStrRet[0].length() == 0){
                StringBuilder tmpSbMsg = new StringBuilder();
                //解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if(tmpBkReader != null){
                    String tmpRespCode = tmpBkReader.getFirstText("/ap/RespCode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                    String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                    String tmpRespSource = tmpBkReader.getFirstText("/ap/RespSource");

                    retDetail.respCode = "0";
                    retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                    retDetail.transState = tmpRespSource + "+" + tmpRespCode;
                    /*String tmpWaitFlag = tmpBkReader.getFirstText("/ap/Corp/WaitFlag");
                    if(tmpWaitFlag != null && tmpWaitFlag.length() > 0){
                        retDetail.transState = retDetail.transState + "+" + tmpWaitFlag;
                    }*/
                    retDetail.payInfoCode = tmpRespCode;
                    retDetail.respInfo = StringHelper.joinNotEmpty("+", tmpRetInfo,tmpRetRxtInfo);
                }
                else{
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            }
            else if(tmpStrRet[0].equals(ConnState.FAIL)){
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            }
            else{
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();

            retDetail.respCode = "-1";
            retDetail.respInfo = ex.getMessage();

            WriteBankLogLn(ex);
        }
        if (retDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(retDetail.reqSeqID)) {
            retDetail.reqSeqID = exchangePay.singleDetail.askNumber;
        }
        retAts.writeRetDetail(retDetail);
        return retAts;
    }

    @Override
    //
    public RetAtsExchange qryExchangePay(ReqQryExchange exchangeQry) throws Exception {
        //返回ATS的对象
        RetAtsExchange retAts = new RetAtsExchange(exchangeQry.reqHeader);

        RetAtsExchangeDetail tmpRetAtsDetail = new RetAtsExchangeDetail();
        tmpRetAtsDetail.respCode = "";
        String contlast = "";
        if(tmpRetAtsDetail.respCode.length() == 0){
            ABC02Header bankHeader = new ABC02Header();
            bankHeader.CCTransCode = "GQ18LX";
            bankHeader.ReqSeqNo = exchangeQry.reqHeader.transSeqID;
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
            xmlWriter.writeStartElement("Cmp");
            xmlWriter.writeElementString("DbProv", exchangeQry.payAreaCode);
            xmlWriter.writeElementString("DbAccNo", this.getAbcAccNo(exchangeQry.payAct));
            xmlWriter.writeElementString("DbCur",this.convertCurToBank(exchangeQry.payCur));
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("atii");
            xmlWriter.writeElementString("cn", getBankConfig().getValueAsString("contractNo"));
            xmlWriter.writeElementString("bstype", "1");//0结汇 1售汇
            xmlWriter.writeElementString("trnfromstat", "0");//交易状态 0未受理,1已受理,2拒绝,3成交 先默认为0
            xmlWriter.writeElementString("begdate", Format.Date8Format.format(exchangeQry.getBgnDateTime()));//起始日期
            xmlWriter.writeElementString("enddate", Format.Date8Format.format(exchangeQry.getBgnDateTime()));//结束日期
            xmlWriter.writeElementString("trnminamt", "");//结售汇最小金额
            xmlWriter.writeElementString("trnmaxamt", "");//结售汇最大金额
            xmlWriter.writeElementString("cbuyccyacc", "");//买入币种清算账号
            xmlWriter.writeElementString("csellccyacc", "");//卖出币种清算账号
            xmlWriter.writeEndElement();
            xmlWriter.writeStartElement("Cme");
            xmlWriter.writeElementString("ContLast", contlast,true);
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            try{
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if(tmpStrRet[0].length() == 0){
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if(tmpBkReader != null){
                        String tmpRespCode = tmpBkReader.getFirstText("/ap/RespCode");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/RespInfo");
                        String tmpRetRxtInfo = tmpBkReader.getFirstText("/ap/RxtInfo");
                        //String tmpRespSource = tmpBkReader.getFirstText("/ap/RespSource");

                        if (tmpRespCode.equals("0000")){
                            //当ContFlag为1时，CC将前次应答报文返回的Cme/ContLast作为新一次请求节点上送。
                            /*String contFlag = tmpBkReader.getFirstText("/ap/Cmp/ContFlag");
                            if("0".equals(contFlag)){

                            }else if("1".equals(contFlag)){
                                contlast = tmpBkReader.getFirstText("/ap/Cme/ContLast");
                                xmlWriter.writeFirstElement("/ap/Cme/ContLast",contlast);
                                String[] tmpStrRet1 = sendToBank(xmlWriter.toXmlString());
                                if(tmpStrRet1[0].length() == 0){


                                }else {
                                    tmpRetAtsDetail.respCode = "-1";
                                    tmpRetAtsDetail.respInfo = tmpStrRet[1];
                                }
                            }*/
                            int tmpRecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/RecordNum"));
                            int tmpFieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/Cme/FieldNum"));
                            if(tmpRecordNum > 0){
                                String tmpDataMFS = "";
                                String tmpFileFlag = tmpBkReader.getFirstText("/ap/FileFlag");
                                if(tmpFileFlag != null && tmpFileFlag.equals("1")){
                                    String tmpBatchFileName = tmpBkReader.getFirstText("/ap/Cmp/BatchFileName");
                                    String tmpFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator)+File.separator + tmpBatchFileName;
                                    this.WriteBankLogLn("读取前置数据文件：" + tmpFilePath);
                                    tmpDataMFS = FileHelper.readFileText(tmpFilePath, getCharset());
                                    if(tmpDataMFS == null){
                                        this.WriteBankLogLn("读取前置数据文件返回完全，需确认前置文件夹配置和文件是否存在");
                                    }
                                    else{
                                        this.WriteBankLogStep3(tmpDataMFS);
                                    }
                                }
                                else{
                                    tmpDataMFS = tmpBkReader.getFirstText("/ap/Cmp/RespPrvData");
                                }
                                if(tmpDataMFS != null){
                                    StringBuilder tmpSbLog = new StringBuilder();
                                    ArrayList<String[]> tmpArrayList = MFSHelper.getTextArray(tmpDataMFS, "|", tmpFieldNum, tmpRecordNum, tmpSbLog);
                                    if(tmpSbLog.length() == 0){
										/*
									TrDate|TrTime|ContractNo|CifNo|Name|CorpNo|ValDate|BsType|Project|TrType|TrStep|BuyCur|SellCur|BuyAcc|SellAcc|BuyAmt|SellAmt|Price|Status|TrFrom|TrSeqNo|
									0交易日期|1交易时间|2合约编码|3客户号|4客户名称|5组织机构代码|6交割日期|7业务类型|8结售汇项目|9交易类型|
									10交易步骤|11买入币种|12卖出币种|13买入账号|14卖出账号|15买入金额|16卖出金额|17成交价|18业务受理状态|19交易来源|20交易流水
										 * */
                                        for(int i=0;i<tmpArrayList.size();i++){
                                            String[] tmpEachArr = tmpArrayList.get(i);
                                            tmpRetAtsDetail.respCode = "0";
                                            tmpRetAtsDetail.respInfo =  tmpRetInfo;
                                            tmpRetAtsDetail.reqSeqID =  tmpEachArr[20];
                                            tmpRetAtsDetail.transState = tmpRespCode+"+"+tmpEachArr[18];//0	未受理1已受理2拒绝3成交 todo ATS未维护
                                            tmpRetAtsDetail.payInfoCode = tmpRespCode+"+"+tmpEachArr[18];
                                        }
                                    }
                                    else{
                                        tmpRetAtsDetail.respCode = "-1";
                                        tmpRetAtsDetail.respInfo = tmpSbLog.toString();
                                    }
                                }
                                else{
                                    tmpRetAtsDetail.respCode = "-1";
                                    tmpRetAtsDetail.respInfo = "数据为空";
                                }
                            }
                        }
                        else{
                            tmpRetAtsDetail.respCode = "-1";
                            if(!StringHelper.isNullOrEmpty(tmpRetRxtInfo)){
                                tmpRetAtsDetail.respInfo = tmpRetRxtInfo;
                            }
                            else{
                                tmpRetAtsDetail.respInfo = tmpRetInfo;
                            }
                        }
                    }
                    else{
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                    }
                }
                else{
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpStrRet[1];
                }
            }
            catch (Exception e) {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = e.getMessage();
                e.printStackTrace();
            }
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }
}
